package com.example.core.filter;

import com.example.core.context.GatewayContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Peng Yisheng
 * @Date 2024/12/1 21:35
 * @Description 网关请求的过滤器链 存储需要执行的过滤器列表 默认按照顺序进行执行（过滤器链工厂中实现的）
 */
@Slf4j
public class GatewayFilterChain {

    private List<Filter> filters = new ArrayList<>();

    public GatewayFilterChain addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }

    public GatewayFilterChain addFilterList(List<Filter> filter) {
        filters.addAll(filter);
        return this;
    }

    public GatewayContext doFilter(GatewayContext ctx) throws Exception {
        if (filters.isEmpty()) {
            return ctx;
        }
        try {
            // 执行所有的过滤器
            for (Filter fl : filters) {
                fl.doFilter(ctx);
                if (ctx.isTerminated()) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("执行过滤器发生异常,异常信息：{}", e.getMessage());
            throw e;
        }
        return ctx;
    }
}
